import articleModule from "@/modules/article";
import blogModule from "@/modules/blog";
import { NextResponse } from "next/server";

export async function GET(request, { params }) {
  const { slug } = await params;
  const limit = Number(request.nextUrl.searchParams.get("limit")) || 10;
  const page = Number(request.nextUrl.searchParams.get("page")) || 1;
  const offset = (page - 1) * limit;
  let articlesData = [];
  if (!!slug && slug !== 'all') {
    const blogId = await blogModule.getBySlug(slug);
    if (!blogId) { return NextResponse.json({ message: "Blog not found" }, { status: 404 }); }
    articlesData = await articleModule.getByBlogId(blogId.id, limit, offset);
  } else {
    articlesData = await articleModule.get(limit, offset);
  }
  if (!articlesData) { return NextResponse.json({ message: "Article not found" }, { status: 404 }); }
  return NextResponse.json({ message: 'Article found', articles: articlesData.articles, total: articlesData.total, activeTotal: articlesData.activeTotal });
}